import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Input, message as msg} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {getDetail} from './api';
import {injectIntl} from './intl';
import {formatAmount, conventEnumValueToString} from '../utils';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import {rejectValidator} from './validator';
import {transportType, paymentType, partOrderPriceTerms, currency} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import Export from '../common/Export';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import LocalizeInputNumber from '../common/LocalizeInputNumber';

const {Description} = DescriptionList;
const FormItem = Form.Item;
class ApprovePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: []
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details.map(v => Object.assign({}, v, {
                                isDealerUser: this.props.isDealerUser,
                                price: v.price ? v.price : v.estimatedPrice,
                                approvedQuantity: v.planQuantity
                            }))
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    setRowClassName(record) {
        if(record.estimatedPrice && !record.isDealerUser)
            return styles.rowRedStyle;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, details} = this.state;
        this.setState({loading: true});
        this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitReject = () => {
        const {data, details} = this.state;
        const isValid = rejectValidator(data, details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmitReject(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onUpdateQuantity = (approvedQuantity, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.partId === id) {
                if(approvedQuantity && d.minPackSize && !Number.isInteger(approvedQuantity / d.minPackSize))
                    msg.warn(this.props.intl.formatMessage({
                        id: 'approvePanel.message.planQuantityMinPackSize',
                        defaultMessage: '备件最小包装数大于0时，备件清单的订货数量是最小包装数的整数倍'
                    }));
                return Object.assign({}, d, {
                    approvedQuantity
                });
            }
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const validateApprovedContent = ((data.approvedContent && data.approvedContent.length > 100) || !data.approvedContent) && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.approve, this.props.permissions);
        const currentSelectRowkeys = details.map(item => item.partId);
        details.forEach(r => currentSelectRowkeys.push(r.oldPartId));
        let totalNumber = 0;
        let totalKind = 0;
        let totalPrice = 0;
        if(this.state.details) {
            totalKind = this.state.details.length;
            this.state.details.forEach(d => {
                totalNumber += (d.planQuantity);
                totalPrice += (d.planQuantity * d.price);
            });
        }
        const colums = [{
            title: formatMessage({
                id: 'approvePanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
            width: 300,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
            render: text => <Ellipsis tooltip fullWidthRecognition length={60}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'approvePanel.column.unit',
                defaultMessage: '计量单位'
            }),
            dataIndex: 'unit',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.minPackSize',
                defaultMessage: '最小包装数'
            }),
            dataIndex: 'minPackSize',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            width: 120,
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.planQuantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'planQuantity',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.stockQuantity',
                defaultMessage: '库存数量'
            }),
            dataIndex: 'stockQuantity',
            width: 120,
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.column.approvedQuantity',
                defaultMessage: '审核量'
            })}</span>,
            dataIndex: 'approvedQuantity',
            width: 100,
            render: (text, record) => {
                const validate = (!text || text === undefined) || text === 0 ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            min={0}
                            id={record.partId}
                            precision={0}
                            value={text} onBlur={this.onUpdateQuantity}/>
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'approvePanel.column.currentStockQty',
                defaultMessage: '当前库存'
            }),
            dataIndex: 'currentStockQty',
            width: 120,
        }, {
            title: formatMessage({
                id: 'approvePanel.column.averageSalesQty',
                defaultMessage: '近6个月月均销量'
            }),
            dataIndex: 'averageSalesQty',
            width: 120,
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'approvePanel.column.common',
                        defaultMessage: '基础信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.code',
                                        defaultMessage: '订单编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'approvePanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">({data.dealerCode}) {data.dealerName}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.customerOrderCode',
                                        defaultMessage: '客户订单编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.customerOrderCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'approvePanel.operation.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">({data.brandCode}) {data.brandName}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.operation.partOrderType',
                                            defaultMessage: '订单类型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.partOrderTypeName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.operation.transportType',
                                            defaultMessage: '运输方式'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(transportType, data.transportType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.operation.paymentType',
                                            defaultMessage: '付款方式'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(paymentType, data.paymentType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.operation.partOrderPriceTerms',
                                            defaultMessage: '价格条款'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partOrderPriceTerms, data.partOrderPriceTerms)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.account',
                                        defaultMessage: '到付账号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.account}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.carier',
                                        defaultMessage: '指定货代'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.carier}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receivedCompany',
                                        defaultMessage: '收货方'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.receivedCompany}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receivedTelephone',
                                        defaultMessage: '收货方电话'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.receivedTelephone}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receivedPerson',
                                        defaultMessage: '收货联系人'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.receivedPerson}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receivedPersonPhone',
                                        defaultMessage: '收货人联系电话'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.receivedPersonPhone}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receivedPort',
                                        defaultMessage: '目的港口'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.receivedPort}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.shipmentPort',
                                        defaultMessage: '发运港口'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.shipmentPort}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receivedAddress',
                                        defaultMessage: '收货地址'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.receivedAddress}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.approvedContent',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item}
                                    validateStatus={validateApprovedContent}
                                    required>
                                        <TextInput
                                            type="textarea"
                                            name="approvedContent"
                                            value={data.approvedContent}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.operation.detail',
                            defaultMessage: '订单清单'
                        })}
                        extra={<div>
                            <Export key={'export'} exportRequest={() => this.props.onClickDetailExport(data.id)} />
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="partId"
                            dataSource={details}
                            rowClassName={this.setRowClassName}
                            pagination={false}
                            footer={() => <DescriptionList><Description term={formatMessage({
                                id: 'approvePanel.operation.totalNumber',
                                defaultMessage: '订购量汇总'
                            })}>{totalNumber}
                            </Description><Description term={formatMessage({
                                id: 'approvePanel.operation.totalKind',
                                defaultMessage: '品种汇总'
                            })}>{totalKind}
                            </Description>
                            <Description term={formatMessage({
                                id: 'approvePanel.operation.totalPrice',
                                defaultMessage: '金额汇总'
                            })}>{formatAmount(totalPrice)}
                            </Description></DescriptionList>}
                            scroll={{
                                x: 'max-content',
                                y: 800
                            }}
                            size="small"
                            bordered={true} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            onClick={this.onSubmitReject}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmitReject',
                                defaultMessage: '驳回'
                            })}
                        </Button>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    brands: PropTypes.array.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickDetailExport: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onSubmitReject: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onApprove,
    onReject,
    detailExportApprove
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return brands;
    }
);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    brands: getinitEnumData(state),
    enterprise: getEnterprise(state),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onApprove(data, details)),
    onSubmitReject: (data, details) => dispatch(onReject(data, details)),
    onClickDetailExport: id => dispatch(detailExportApprove(id)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
